// sysenv.cpp
#include "SysEnv.h"
#include <QStandardPaths>
#include <QDir>
#include <QFileInfo>
#include <QHostAddress>
#include <QCoreApplication>

SysEnv& SysEnv::instance()
{
    static SysEnv env;
    return env;
}

void SysEnv::setConfigInAppDir(const QString &relativePath)
{
    QString configDir = QCoreApplication::applicationDirPath();
    QString fullPath = configDir + "/" + relativePath;

    // 确保目录存在
    QFileInfo fileInfo(fullPath);
    QDir dir = fileInfo.dir();
    if (!dir.exists()) {
        dir.mkpath(".");
    }

    setIniPath(fullPath);
}

void SysEnv::setIniPath(const QString &absoluteFilePath)
{
    if (m_iniPath == absoluteFilePath) {
        return; // 路径未变化
    }

    // 确保目录存在
    QFileInfo fileInfo(absoluteFilePath);
    QDir dir = fileInfo.dir();
    if (!dir.exists()) {
        dir.mkpath(".");
    }

    m_iniPath = absoluteFilePath;

    // 重新初始化 QSettings
    if (m_ini) {
        m_ini->sync();
        delete m_ini;
    }

    m_ini = new QSettings(m_iniPath, QSettings::IniFormat, this);
    load(); // 重新加载配置
}

SysEnv::SysEnv(QObject* parent)
    : QObject(parent)
{
    // 使用默认路径初始化 QSettings
    m_ini = new QSettings(QSettings::IniFormat,
                          QSettings::UserScope,
                          "MyCompany", "MyApp", this);
    load(); // 启动即加载
}

/* ---------- 加载 ---------- */
void SysEnv::load()
{
    if (!m_ini) {
        return;
    }

    /* Persistent */
    m_cfg.serverIP   = m_ini->value("Net/ServerIP", DEFAULT_SERVER_IP).toString();
    m_cfg.serverPort = m_ini->value("Net/ServerPort", DEFAULT_SERVER_PORT).toInt();
    m_cfg.theme      = m_ini->value("UI/Theme", DEFAULT_THEME).toString();
    m_cfg.imageSavePath = m_ini->value("Save/ImagePath", DEFAULT_IMAGE_SAVE_PATH).toString();
    m_cfg.imageSaveDays = m_ini->value("Save/ImageSaveDays", DEFAULT_IMAGE_SAVE_DAYS).toInt(); // 新增
    m_cfg.autoStart     = m_ini->value("AutoStart/Enabled", DEFAULT_AUTO_START).toBool();  // 新增

    // 验证加载的配置
    if (!isConfigValid()) {
        // 重置为默认值
        m_cfg.serverIP = DEFAULT_SERVER_IP;
        m_cfg.serverPort = DEFAULT_SERVER_PORT;
        m_cfg.theme = DEFAULT_THEME;
        m_cfg.imageSavePath = DEFAULT_IMAGE_SAVE_PATH;
        m_cfg.imageSaveDays = DEFAULT_IMAGE_SAVE_DAYS;
        m_cfg.autoStart = DEFAULT_AUTO_START;  // 重置为默认值
    }
}

/* ---------- 保存 ---------- */
void SysEnv::save()
{
    if (!m_ini) {
        return;
    }

    // 验证配置 before saving
    if (!isConfigValid()) {
        return;
    }

    /* Persistent */
    m_ini->setValue("Net/ServerIP", m_cfg.serverIP);
    m_ini->setValue("Net/ServerPort", m_cfg.serverPort);
    m_ini->setValue("UI/Theme", m_cfg.theme);
    m_ini->setValue("Save/ImagePath", m_cfg.imageSavePath);
    m_ini->setValue("Save/ImageSaveDays", m_cfg.imageSaveDays);
    m_ini->setValue("AutoStart/Enabled", m_cfg.autoStart);  // 新增

    m_ini->sync(); // 立即写盘
    emit cfgChanged();
}

void SysEnv::setRunning(bool on)
{
    if (m_rt.running == on) {
        return;
    }
    m_rt.running = on;
    emit runningChanged(on);
}

QString SysEnv::getImageSavePath() const
{
    if (m_cfg.imageSavePath.isEmpty()) {
        // 如果未设置，返回默认路径（应用程序目录下的capture_root）
        return QCoreApplication::applicationDirPath() + "/capture_root";
    }
    return m_cfg.imageSavePath;
}

void SysEnv::setImageSavePath(const QString &path)
{
    if (m_cfg.imageSavePath == path) {
        return;
    }

    m_cfg.imageSavePath = path;
    save();
}

// 新增：获取图像保存天数
int SysEnv::getImageSaveDays() const
{
    return m_cfg.imageSaveDays;
}

// 新增：设置图像保存天数
void SysEnv::setImageSaveDays(int days)
{
    if (m_cfg.imageSaveDays == days) {
        return;
    }

    m_cfg.imageSaveDays = days;
    save();
}

// 新增：获取自启动设置
bool SysEnv::getAutoStart() const
{
    return m_cfg.autoStart;
}

// 新增：设置自启动
void SysEnv::setAutoStart(bool enable)
{
    if (m_cfg.autoStart == enable) {
        return;
    }

    m_cfg.autoStart = enable;
    save();  // 自动保存到配置文件
}

void SysEnv::setBit(quint8 bit, bool bad)
{
    quint8 old = m_rt.initMask;
    if (bad) {
        m_rt.initMask |= bit;
    } else {
        m_rt.initMask &= ~bit;
    }

    if (old != m_rt.initMask) {
        emit initDone(m_rt.initMask);
    }
}

bool SysEnv::isConfigValid() const
{
    // 验证服务器IP格式
    QHostAddress address;
    if (!address.setAddress(m_cfg.serverIP)) {
        return false;
    }

    // 验证端口范围
    if (m_cfg.serverPort < 1 || m_cfg.serverPort > 65535) {
        return false;
    }

    // 验证主题
    if (m_cfg.theme.isEmpty() ||
        (m_cfg.theme != "Light" && m_cfg.theme != "Dark")) {
        return false;
    }

    // 验证图像保存天数范围
    if (m_cfg.imageSaveDays < 1 || m_cfg.imageSaveDays > 3650) {
        return false;
    }

    // 验证图像保存路径（如果设置了自定义路径）
    if (!m_cfg.imageSavePath.isEmpty()) {
        QFileInfo pathInfo(m_cfg.imageSavePath);
        if (!pathInfo.isDir()) {
            // 如果路径不存在，尝试创建
            QDir dir;
            if (!dir.mkpath(m_cfg.imageSavePath)) {
                return false;
            }
        }
    }

    // 自启动设置是布尔值，不需要额外验证

    return true;
}
